import { Component, OnInit } from '@angular/core';
import { NavParams, NavController, ModalController } from '@ionic/angular';
import { CacheService } from '@services/cache.service';
import { InstallService } from '@services/data.service/index';
import { MyNoteService } from '@services/myNote.service';
import { ActivatedRoute } from '@angular/router';
import { DatePipe } from '@angular/common';
import { EmitService } from '@services/emit.service';
import { DeviceSelectModal } from '@modals/device-select/device-select';

@Component({
    selector: 'instrument',
    templateUrl: 'instrument.html',
    styleUrls: ['instrument.scss']
})

export class InstrumentPage implements OnInit {
    stack;              // 数据栈
    InstallList = [];   // 仪表
    areaName;
    areaId;
    projectName;
    projectId;
    installData;
    stackList;  // 关联数据栈列表

    defaultExtend = {
        userId: null,
        userName: null,
        step: null,                         // 当前进行到第几步
        state: null,                        // 设备状态（0-未开始；1-进行中 ；2-已结束有问题；3-已结束无问题）
        startTime: null,                    // 开始时间
        Address: null,                      // 扫码得到的设备地址
        Code: null,                         // 扫码得到的编号
        endTime: null,                      // 结束时间
        data1: null,                     // 扫描结果
        data2: null,                     // {a：安装示意图 ；b：拍照（图片路径+时间）；c:仪表-位置选择（例如：天花板）}
        data3: null,                     // {a：接线示意图 ； b：拍照（图片路径+时间） }
        data4: null,                     // {a:激活状态 ；b：激活次数 }（便于处于进行时设备的判断）
        data5: null,                     // 保存初始化的数据设置
        data6: null,                     // {a:采集参数列表 ; b:列表勾选情况; c : endTime }
        data7: null,
        areaId: null,
        meterId: null,
        mapping: null,                    // 安装位置
    };

    constructor(private navCtrl: NavController,
        private cache: CacheService,
        private installService: InstallService,
        private myNote: MyNoteService,
        private emitService: EmitService,
        private modalCtrl: ModalController,
        private datePipe: DatePipe
    ) {
        this.areaId = this.emitService.installState.areaId || '';
        this.areaName = this.emitService.installState.areaName || '';
        this.projectId = this.cache.currentProject.projectId;
        this.projectName = this.cache.currentProject.projectName;
    }

    ngOnInit() {
    }

    // 进入界面刷新仪表状态
    ionViewWillEnter() {
        this.projectId = this.cache.currentProject.projectId;
        this.installService.getInstallData(this.projectId, this.areaId).subscribe(res => {
            if (res) {
                this.installData = res;
            }
            console.log('缓存的安装进度', this.installData);
            this.getAreaInfo();
        });
    }

    getAreaInfo() {
        this.installService.getAreaInfo(this.projectId, this.areaId).subscribe(res => {
            res.data.stack.bType = 1;
            for (const data of res.data.meters) {
                data.bType = 2;
            }
            this.stack = res.data.stack;
            this.InstallList = res.data.meters;
            this.stackList = res.data.stackList;
            for (const data of this.stackList) {
                data.bType = 1;
                data.canCheck = true;
                data.areaId = this.areaId;
                data.name = data.stackName;
            }

            // 判断仪表状态   state = 0 - 未安装
            if (this.installData) {
                for (let i = 0; i < this.InstallList.length; i++) {
                    if (this.installData[this.InstallList[i].meterId]) {
                        this.InstallList[i].state = this.installData[this.InstallList[i].meterId].state;
                    } else {
                        this.InstallList[i].state = 0;
                    }
                }
                if (this.installData[0]) {
                    if (this.stack.stackId === this.installData[0].stackId) {
                        this.stack.state = this.installData[0].state;
                    }
                }
            }
        });
    }


    toProcess(item, i?) {
        console.log('点击的仪表', item);

        if (i === undefined) {
            item.meterId = 0;
        };
        const bType = item.bType;
        const bId = item.bType === 1 ? item.stackId : item.meterId;
        this.installService.getProgress(bType, bId).subscribe(res => {
            if (res.data) {
                console.log('加载远程进度');
                const data = {
                    Type: 0,
                    areaName: this.areaName,
                    meterName: item.meterName || item.stackName,
                    device: item,
                    mapping: item.mapping || null,
                    selected: null,
                    Relation: item.Relation || null,
                    meterLevel: item.meterLevel || null,
                    installData: null,
                    parameter: {
                        UID: null,
                        PID: null,
                    }
                };
                // 数据栈
                if (bId === item.stackId && item.meterId === 0) {
                    this.saveInstall(data, item, i, res.data);
                } else if (bId && item.meterId && bId === item.meterId) {
                    // 仪表
                    this.saveInstall(data, item, i, res.data);
                }
            } else {
                console.log('加载本地进度', this.installData);
                if (this.installData && this.installData[item.meterId] && this.installData[item.meterId]) {
                    item.mapping = this.installData[item.meterId].mapping || null;
                    item.Relation = this.installData[item.meterId].Relation || null;
                    item.meterLevel = this.installData[item.meterId].meterLevel || null;
                    item.pid = this.installData[item.meterId].meterLevel ? this.installData[item.meterId].meterLevel.id : null;
                }
                const data = {
                    Type: 0,
                    areaName: this.areaName,
                    meterName: item.meterName || item.stackName,
                    device: item,
                    mapping: item.mapping || null,
                    selected: null,
                    Relation: item.Relation || null,
                    meterLevel: item.meterLevel || null,
                    installData: null,
                    parameter: {
                        UID: null,
                        PID: null,
                    }
                };
                Object.assign(this.defaultExtend, data.device);
                this.goPage(data, item, i);
            }
        });
    }

    // 页面跳转
    goPage(data, item, i) {
        if (i === undefined) {  // 数据栈
            this.emitService.installParams = data;
            console.log('数据栈', this.emitService.installParams);
            data.Type = 0;
            data.device.meterId = 0;
            this.navCtrl.navigateForward(['tabs/my/InstallationPage']);
        } else {
            data.Type = 1;
            data.parameter.PID = item.pid;
            data.parameter.UID = this.stack.stackId;
            this.emitService.installParams = data;
            console.log('仪表', this.emitService.installParams);
            if (item.canInstall) {  // 仪表
                if (item.isChildSensor) {
                    if (item.isActive) {
                        this.navCtrl.navigateForward(['tabs/my/InstallationPage']);
                    } else {
                        this.emitService.installParams.isChildSensor = true;
                        if (this.emitService.installParams.meterLevel || item.isInstalled) {
                            this.navCtrl.navigateForward(['tabs/my/InstallationPage']);
                        } else {
                            this.navCtrl.navigateForward(['tabs/my/InstallSelectPage'], { queryParams: { meterType: 'isChildSensor' } });
                        }
                    }
                } else if (item.meterModelId === 1007 || item.meterModelId === 1017) {
                    // PIO1900-M仪表 及 PIO1900Q-M仪表
                    this.emitService.installParams.isPIOM = true;
                    if (this.emitService.installParams.Relation || item.isInstalled) {
                        this.navCtrl.navigateForward(['tabs/my/InstallationPage']);
                    } else {
                        this.navCtrl.navigateForward(['tabs/my/InstallSelectPage'], { queryParams: { meterType: 'isPIOM' } });
                    }
                } else {
                    this.navCtrl.navigateForward(['tabs/my/InstallationPage']);
                }
            } else {
                this.myNote.MyNotice(item.alarmInfo);
            }
        }
    }

    // 若数据栈不存在则提供推荐选择
    async checkStack() {
        const data = {
            title: '请选择数据栈',
            device: this.stackList,
            select: this.stack.stackId || null
        };
        const modal = await this.modalCtrl.create(
            {
                component: DeviceSelectModal,
                componentProps: data
            });
        modal.present();
        const selectData = await modal.onDidDismiss();
        if (selectData.data) {
            this.getAreaInfo();
            this.stack = selectData.data;
            // 判断仪表状态   state = 0 - 未安装
            if (this.installData) {
                if (this.installData[0]) {
                    if (this.stack.stackId === this.installData[0].stackId) {
                        this.stack.state = this.installData[0].state;
                    }
                }
            }
        }
    }

    // 将后台安装进度放入对应仪表
    saveInstall(data, item, i, res) {
        item.isInstalled = true;
        // 处理初始值
        if (res.deployParams && res.deployParams.length) {
            for (const dat of res.deployParams) {
                dat.key = dat.paramId;
                dat.title = dat.paramName;
                dat.defaultValue = [dat.value];
                dat.defaultName = dat.valueName ? [dat.valueName] : null;
            }
        }
        this.defaultExtend.areaId = item.areaId || null;
        this.defaultExtend.meterId = item.meterId || null;
        this.defaultExtend.userName = res.userName || null;
        this.defaultExtend.step = res.step || null;
        this.defaultExtend.mapping = res.address || null;
        this.defaultExtend.startTime = this.datePipe.transform(res.startTime, 'yyyy-MM-dd HH:mm:ss') || null;
        this.defaultExtend.endTime = this.datePipe.transform(res.endTime, 'yyyy-MM-dd HH:mm:ss') || null;
        this.defaultExtend.data1 = res.card || null;
        this.defaultExtend.data5 = res.deployParams || null;
        this.defaultExtend.data6 = {
            CodeInfo1: null,
            CodeInfo2: null,
            CodeInfo3: null
        };
        this.defaultExtend.data6.CodeInfo3 = res.datas || null;
        const installData = this.defaultExtend;
        console.log('加载后台进度', installData);
        data.installData = installData;
        // this.installService.saveInstallData(item.areaId, item.meterId, installData);
        this.goPage(data, item, i);
    }

}
